package com.ycy.plugin.digest;

import com.ycy.plugin.code.CodeAlgorithm;
import com.ycy.plugin.config.Config;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;

/**
 * 摘要算法
 */
public class MessageDigestAlgorithm {

  public static final String KEY_SHA = "SHA";

  public static final String KEY_MD5 = "MD5";

  /**
   * MAC算法可选以下多种算法
   * <pre>
   * HmacMD5
   * HmacSHA1
   * HmacSHA256
   * HmacSHA384
   * HmacSHA512
   * </pre>
   */
  public static final String KEY_MAC = "HmacMD5";

  /**
   * @param src
   * @param secretType SHA 、MD5
   */
  public static byte[] encrypt(String src, String secretType) throws Exception {
    byte[] data = src.getBytes(StandardCharsets.UTF_8);
    MessageDigest sha = MessageDigest.getInstance(secretType);
    sha.update(data);
    return sha.digest();
  }

  /**
   * MAC加密
   */
  public static byte[] encryptHMAC(String src, String secretType, String secretkey) throws Exception {
    byte[] data = src.getBytes(StandardCharsets.UTF_8);
    byte[] bytes = secretkey.getBytes(StandardCharsets.UTF_8);
    SecretKey secretKey = new SecretKeySpec(bytes, secretType);
    Mac mac = Mac.getInstance(secretType);
    mac.init(secretKey);
    return mac.doFinal(data);
  }

  public static String hash(String secretType, String secretKey, String data, String out, String toCase) throws Exception {
    if (secretType == null) {
      throw new RuntimeException("secretType 未指定");
    }
    secretType = secretType.toLowerCase();
    byte[] bytes;
    if (secretType.startsWith("hmac")) {
      bytes = encryptHMAC(data, secretType, secretKey);
    } else {
      bytes = encrypt(data, secretType);
    }
    String encryptStr = Config.hex.equalsIgnoreCase(out) ? CodeAlgorithm.HexEncode(bytes) : CodeAlgorithm.Base64Encode(bytes);
    if (Config.touppercase.equalsIgnoreCase(toCase)) {
      return encryptStr.toUpperCase();
    }
    if (Config.tolowercase.equalsIgnoreCase(toCase)) {
      return encryptStr.toLowerCase();
    }
    return encryptStr;
  }

  public static void main(String[] args) {
    try {
      String s = "19A/8O9E8ZFh7viRmQIRUWf0J5jgAuOL9Ng9WUr9FfHQ=202109061431040001";
      String hash = MessageDigestAlgorithm.hash("HmacMD5", "1234567890abcdef", s, "hex", "tolowercase");
      System.out.println(hash);
    } catch (Exception e) {
      e.printStackTrace();
    }



  }

}
